import interact from "interactjs"
// 栅格大小
const gridWidth = 20

const restrictToParent = interact.modifiers.restrict({
  restriction: "parent",
  elementRect: { left: 0, right: 1, top: 0, bottom: 1 },
})

const gridSnap = interact.modifiers.snap({
  targets: [interact.createSnapGrid({ x: gridWidth, y: gridWidth })],
  range: Infinity,
  relativePoints: [{ x: 0, y: 0 }],
  offset: "parent",
})

const restrictToParentSize = interact.modifiers.restrict({
  restriction: "parent",
  // elementRect: { left: 0, right: 1, top: 0, bottom: 1 }
})

const onMove = event => {
  var target = event.target
  var left = (Math.round(parseFloat(target.style.left)) || 0) + event.dx
  var top = (Math.round(parseFloat(target.style.top)) || 0) + event.dy

  target.style.left = left + "px"
  target.style.top = top + "px"
}

const onResize = event => {
  var target = event.target
  var left = parseFloat(target.style.left) || 0
  var top = parseFloat(target.style.top) || 0

  target.style.width = Math.round(event.rect.width) + "px"
  target.style.height = Math.round(event.rect.height) + "px"

  left += Math.round(event.deltaRect.left)
  top += Math.round(event.deltaRect.top)

  target.style.left = left + "px"
  target.style.top = top + "px"
}

const dragResize = (target, callback) => {
  interact(target).unset()
  interact(target)
    .draggable({
      inertia: false,
      modifiers: [restrictToParent, gridSnap],
      onmove: onMove,
      onend(event) {
        callback(event.target)
      },
    })
    .resizable({
      edges: {
        top: true,
        left: true,
        bottom: true,
        right: true,
      },
      modifiers: [gridSnap, restrictToParentSize],
      onmove: onResize,
      onend(event) {
        callback(event.target)
      },
    })
}

/**
 * 根据路径和值生成对象
 * @param  {string} path - 对象的路径， 比如 "chartOption.grid.left
 * @param  {*} val - 值, 比如 20
 * @return {object} - 生成的对象
 * {
 *  chartOption: {
 *    grid: {
 *      left: 20
 *    }
 *  }
 * }
 */
const createObjectByPath = function(path, val) {
  let arr = path.split(".")
  let obj = {}
  let result = obj
  while (arr.length > 1) {
    obj = obj[arr.shift()] = {}
  }
  obj[arr.shift()] = val
  return result
}

export { dragResize, createObjectByPath }
